<template>
  <el-form ref="cuForm" v-loading="formLoading" :model="cuForm" size="mini">
    <div style="width: 90%;margin: 10px auto 20px auto" class="flex justify-center">
      <div style="display: inline-block">
        {{ cuForm.year }}年{{ cuForm.type === 1 ? '上半年' : '下半年' }}{{ cuForm.sum }}万元
      </div>
    </div>
    <div style="width: 90%;margin: 0 auto;text-align: right;line-height: 20px;color: #F56C6C">
      <div>总填写维护目标：{{ upholdTargetSummary }}万</div>
      <div>总填写个人目标：{{ myTargetSummary }}万</div>
      <div>总目标：{{ allTargetSummary }}万</div>
    </div>
    <table class="mailTable">
      <tr class="firstTr header">
        <td class="firstTd" style="width: 10%">月份</td>
        <td style="width: 15%">月度目标/万元</td>
        <td style="width: 10%">周</td>
        <td style="width: 30%">时间</td>
        <td style="width: 10%">目标类别</td>
        <td style="width: 25%">目标/万元</td>
      </tr>
      <template v-if="(cuForm.weekArr||[]).length>0" v-for="(item,index) in cuForm.weekArr">
        <template v-for="(tmp,i) in item.time">
          <tr v-for="(target,t) in tmp.target_arr" :key="index +'_' + i + '_' + t">
            <td v-if="i===0 && t===0" class="firstTd" rowspan="8">
              {{ item.month }}月
            </td>
            <td v-if="i===0 && t===0" rowspan="8">
              {{ getCountStr(item.time) }}
            </td>
            <td v-if="t===0" rowspan="2">
              第{{ i + 1 }}周
            </td>
            <td v-if="t===0" rowspan="2">
              {{ tmp.begin + '~' + tmp.end }}
            </td>
            <td>
              {{ target.type === 1 ? '维护' : '个人' }}
            </td>
            <td>
              <el-form-item :prop="'weekArr.' + index +'.time.' + i +'.target_arr.'+t +'.target'"
                            :rules="{required: true, message: '目标不能为空', trigger: 'blur'}"
              >
                <el-input v-model="target.target" size="mini" type="number" step="0.01">
                  <template slot="append">万</template>
                </el-input>
              </el-form-item>
            </td>
          </tr>
        </template>
      </template>
    </table>
    <div style="margin: 10px;text-align: center">
      <el-button @click="closeThisPage">返回</el-button>
      <el-button type="primary" @click="save">保存</el-button>
    </div>
  </el-form>

</template>

<script>
import { queryWeekList, add as save } from '@/api/workbench/saleWeekTarget'
import { add } from '@/utils/amount'

export default {
  name: 'half_year_target',
  data() {
    return {
      cuForm: {
        sum: 0,
        year: null,
        type: null,
        weekArr: [],
        weekList: []
      },
      formLoading: false
    }
  },
  computed: {
    upholdTargetSummary() {
      let sum = 0
      this.cuForm.weekArr.forEach(item => {
        item.time.forEach(tmp => {
          tmp.target_arr.forEach(target => {
            if (target.target && target.type === 1) {
              sum = add(sum, target.target)
            }
          })
        })
      })
      return sum
    },
    myTargetSummary() {
      let sum = 0
      this.cuForm.weekArr.forEach(item => {
        item.time.forEach(tmp => {
          tmp.target_arr.forEach(target => {
            if (target.target && target.type === 2) {
              sum = add(sum, target.target)
            }
          })
        })
      })
      return sum
    },
    allTargetSummary() {
      return add(this.myTargetSummary, this.upholdTargetSummary)
    }
  },
  created() {
    const uuid = this.$route.query.uuid
    const params = this.$store.state.keep.pageParamsMap.get(uuid)
    if (params) {
      this.cuForm.year = params.year
      this.cuForm.type = params.type
    }
    this.formLoading = true
    queryWeekList({
      year: this.cuForm.year,
      type: this.cuForm.type
    }).then(res => {
      this.formLoading = false
      this.cuForm.year = res.data.year
      this.cuForm.type = res.data.type
      this.cuForm.sum = res.data.sum
      let map = new Map()
      res.data.weekList.forEach(item => {
        if (map.has(item.month)) {
          let arr = map.get(item.month).time
          arr.push({
            week_id: item.week_id,
            date: [item.begin_date, item.end_date],
            begin: item.begin_date,
            end: item.end_date,
            target_arr: [
              {
                type: 1,
                target: null
              },
              {
                type: 2,
                target: null
              }
            ]
          })
        } else {
          let arr = []
          arr.push({
            week_id: item.week_id,
            date: [item.begin_date, item.end_date],
            begin: item.begin_date,
            end: item.end_date,
            target_arr: [
              {
                type: 1,
                target: null
              },
              {
                type: 2,
                target: null
              }
            ]
          })
          map.set(item.month, {
            month: item.month,
            time: arr
          })
        }
      })
      this.cuForm.weekArr = []
      map.forEach((value) => {
        this.cuForm.weekArr.push(value)
      })
    })
  },
  watch: {
    'cuForm.weekArr': {
      handler(val) {
        let arr = []
        val.forEach(item => {
          item.time.forEach(tmp => {
            tmp.target_arr.forEach(target => {
              arr.push({
                week_id: tmp.week_id,
                target: target.target,
                type: target.type
              })
            })
          })
        })
        this.cuForm.weekList = arr
      },
      deep: true
    }
  },
  methods: {
    getCountStr(arr) {
      let count = 0
      arr.forEach(item => {
        if (item.target_arr && item.target_arr.length > 0) {
          item.target_arr.forEach(tmp => {
            if (tmp.target) {
              count = add(count, tmp.target)
            }
          })
        }
      })
      return count
    },
    save() {
      this.$refs.cuForm.validate(flag => {
        if (flag) {
          if (this.checkSumTarget()) {
            this.$confirm('保存后无法修改,确定保存？', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              const loading = this.$loading({
                lock: true,
                text: '保存中',
                spinner: 'el-icon-loading',
                background: 'rgba(0, 0, 0, 0.7)'
              })
              save({ weekTargetList: this.cuForm.weekList }).then(res => {
                if (res.code === 200) {
                  this.closeThisPage()
                  this.$message.success('保存成功')
                } else {
                  this.$message.error('保存失败')
                }
                loading.close()
              }).catch(() => {
                this.$message.error('保存失败')
                loading.close()
              })
            }).catch(() => {

            })
          } else {
            this.$message.error('每周目标总和不能小于本年度目标总和,请调整')
          }
        }
      })
    },
    checkSumTarget() {
      let count = 0
      this.cuForm.weekArr.forEach(tmp => {
        tmp.time.forEach(item => {
          if (item.target_arr && item.target_arr.length > 0) {
            item.target_arr.forEach(tmp => {
              if (tmp.target) {
                count = add(count, tmp.target)
              }
            })
          }
        })
      })
      return count >= this.cuForm.sum
    },
    closeThisPage() {
      this.$store.dispatch('tagsView/closePage', this.$route.name)
    }
  }
}
</script>

<style scoped>
.mailTable {
  width: 90%;
  font-size: 14px;
  margin: 0 auto 10px auto;
  border-collapse: collapse;
}

.mailTable tr td {
  height: 40px;
  line-height: 35px;
  box-sizing: border-box;
  padding: 0 10px;
  border-bottom: 1px solid #E6EAEE;
  border-right: 1px solid #E6EAEE;
  text-align: center;
}

.firstTr td {
  border-top: 1px solid #E6EAEE;
}

.firstTd {
  border-left: 1px solid #E6EAEE;
}

.mailTable tr td.column {
  text-align: center;
  /*border: 1px solid #8c939d;*/
}

.header {
  text-align: center;
  font-size: 18px;
  font-weight: bold;
  margin: 10px auto;
}

.required {
  color: red;
}

/deep/ .el-form-item {
  margin-bottom: 0;
}

/deep/ .el-form-item__content {
  line-height: 0;
  text-align: center;
}

/deep/ td .el-form-item__error {
  position: relative;
  padding: 3px;
}
</style>
